import cachepromise_arrayofstring from "./cachepromise-arrayofstring";
import { changeimgsrc } from "./changeimgsrc";
import { changeimgtolocalpath } from "./changeimgtolocalpath";
import {
    addsubheaders,
    changelinkmd,
    handlecodecopy,
    handleneedtitle,
    headeraddanchor,
} from "./commonloadpage";
import compile_into_dom from "./compile_into_dom";
import { getscopeidofurl } from "./getscopeofurl";
import {
    removeallvalidelements,
    removesomevalidelements,
} from "./removesomevalidelements";
import { scopestylesheet } from "./scopestylesheet";

export const mdpageloader = cachepromise_arrayofstring(async function (
    mdurl: string,
    rawmd: string,

    baseurl: string,
    title: string,
    menulist: string[]
): Promise<{
    toc: string;
    main: string;
    stylecssrules: Set<string>;
    // dependencies: Set<string>;
}> {
    let main: undefined | string;
    let toc: undefined | string;
    const stylecssrules = new Set<string>();
    // const dependencies = new Set<string>();
    const tmpcontainer = document.createElement("div");
    const path = mdurl;
    const childnodes: Node[] = await compile_into_dom(
        stylecssrules,
        rawmd,
        path
    );
    //删除当中的style标签和link标签和script标签
    childnodes.forEach((n: Node) => tmpcontainer.appendChild(n));
    removesomevalidelements(tmpcontainer);
    // resolvetitlesave(states, tmpcontainer, path);
    handleneedtitle(tmpcontainer, /* path,  */ title);
    handlecodecopy(tmpcontainer);

    changelinkmd(menulist, tmpcontainer, path);

    toc = addsubheaders(/* states, */ tmpcontainer, path);
    headeraddanchor(tmpcontainer, path);
    //console.log(tmpcontainer);
    changeimgsrc(tmpcontainer, path);

    await scopestylesheet(
        stylecssrules,
        tmpcontainer,
        path /* , dependencies */
    );
    removeallvalidelements(tmpcontainer);
    if (process.env.PRERENDER) {
        changeimgtolocalpath(tmpcontainer, baseurl);
    }
    const currentmdhtml =
        `<div class='${getscopeidofurl(path)}'>` +
        tmpcontainer.innerHTML +
        `</div>`;
    // console.log(currentmdhtml);

    main = currentmdhtml;
    return { main, toc, /*  dependencies, */ stylecssrules };
});
